//
//  CZStatusPictureView.swift
//  GZWeibo009
//
//  Created by gzxzmac on 16/3/25.
//  Copyright © 2016年 gzxzmac. All rights reserved.
//

import UIKit

import SDWebImage

import YYKit

class CZStatusPictureView: UIView {
    
    var pictureURLs: [NSURL]? {
        didSet {
            let size = layoutImageViews()
            
            // 自己来更新自己的宽度和高度
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
        }
    }
    
    private func layoutImageViews() -> CGSize {
        var resultSize = CGSizeZero
        
        let count = pictureURLs?.count ?? 0
        var itemSize = CGSize(width: CZStatusPictureCellWH, height: CZStatusPictureCellWH)
        
        // 默认3列
        var numberOfColumn = CZStatusPictureMaxColumn
        // 有些情况只有2列
        if count == 2 || count == 4 {
            numberOfColumn = 2
        }
        
        for (index, view) in subviews.enumerate() {
            if index >= count {
                // 多余的张数隐藏掉
                view.hidden = true
            } else {
                // 要显示内容
                view.hidden = false
                
                var origin = CGPointZero
                
                if count == 1 {
                    // 一张图片默认大小
                    itemSize = CGSize(width: CZStatusPictureCellWH * 2, height: CZStatusPictureCellWH * 2)
                }
                
                // 计算 在哪行哪列
                let column = index % numberOfColumn
                let row = index / numberOfColumn
                
                origin.x = CGFloat(column) * (CZStatusPictureCellWH + CZStatusPictureMargin)
                origin.y = CGFloat(row) * (CZStatusPictureCellWH + CZStatusPictureMargin)
                
                view.frame = CGRect(origin: origin, size: itemSize)
                
                let url = pictureURLs![index]
                let imageView = view as! UIImageView
                imageView.sd_setImageWithURL(url, placeholderImage: nil, options: SDWebImageOptions.AvoidAutoSetImage, completed: { (image, error, _, _) -> Void in
                    if error != nil {
                        print("error: \(error)")
                        return
                    }

                    imageView.image = image
                    let width: CGFloat = image.size.width;
                    let height: CGFloat = image.size.height;
                    let scale = (height / width) / (imageView.frame.height / imageView.frame.width);
                    if (scale < 0.99 || isnan(scale)) { // 宽图把左右两边裁掉
                        imageView.contentMode = UIViewContentMode.ScaleAspectFill
                        imageView.layer.contentsRect = CGRectMake(0, 0, 1, 1);
                    } else { // 高图只保留顶部
                        imageView.contentMode = UIViewContentMode.ScaleAspectFill
                        imageView.layer.contentsRect = CGRectMake(0, 0, 1, width / height);
                    }
                })
            }
        }
        
        if count != 0 {
            let maxX = CGRectGetMaxX(subviews[count - 1].frame)
            let maxY = CGRectGetMaxY(subviews[count - 1].frame)
            resultSize = CGSize(width: maxX, height: maxY)
        }
        return resultSize
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(frame: CGRect) {
        super.init(frame: CGRectZero)
        
        addImageViews()
    }
    
    private func addImageViews() {
        
        for i in 0..<9 {
            let imageView = UIImageView()
            
            imageView.userInteractionEnabled = true
            imageView.tag = i
            imageView.clipsToBounds = true
            
            let tapGesture = UITapGestureRecognizer(target: self, action: Selector("didSelectedImageView:"))
            imageView.addGestureRecognizer(tapGesture)
            
            addSubview(imageView)
        }
    }
    
    @objc private func didSelectedImageView(gesture: UITapGestureRecognizer) {
        selectedImageView = gesture.view as? UIImageView
        
        let browser = SDPhotoBrowser()

        browser.sourceImagesContainerView = self

        browser.imageCount = pictureURLs?.count ?? 0

        browser.currentImageIndex = selectedImageView!.tag

        browser.delegate = self
        
        browser.show()
    }
    
    private var selectedImageView: UIImageView?
}

extension CZStatusPictureView: SDPhotoBrowserDelegate {
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let image = selectedImageView?.image
        return image ?? UIImage(named: "avatar")
    }

    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let urlString = pictureURLs![index].absoluteString

        let newString = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        return NSURL(string: newString)
    }
}

//class CZStatusPictureView: UICollectionView {
//    
//    // MARK: - 属性
//    private let ReuseIdentifier = "ReuseIdentifier"
//    
//    /// 要显示的图片URL数组
//    var pictureURLs: [NSURL]? {
//        didSet {
//            // 拿到需要显示的图片的数组后,根据图片的数量来计算配图需要的宽和高
//            let size = calcViewSize()
//            
//            // 自己来更新自己的宽度和高度
//            self.snp_updateConstraints { (make) -> Void in
//                make.size.equalTo(size)
//            }
//            
//            // 当拿到pictureURLs后.来根据pictureURLs的数量重新设置collectionView
//            self.reloadData()
//        }
//    }
//    
//    /// 根据图片的数量来计算配图需要的宽和高
//    /// 这个计算是在cell即将显示的时候做的
//    private func calcViewSize() -> CGSize {
//        layout.itemSize = CGSize(width: CZStatusPictureCellWH, height: CZStatusPictureCellWH)
//        layout.minimumInteritemSpacing = 0
//        layout.minimumLineSpacing = 0
//        
//        let count = pictureURLs?.count ?? 0
//        
//        if count == 0 {
//            return CGSizeZero
//        }
//        
//        // 当调用这个地方的时候,cell是即将显示,图片是已经缓存完成了的
//        // 单图会按照图片 原始尺寸 显示
//        if count == 1 {
//            // 一张图片默认大小
//            let imageSize  = CGSize(width: CZStatusPictureCellWH * 2, height: CZStatusPictureCellWH * 2)
//            
//            layout.itemSize = imageSize
//            
//            return imageSize
//        }
//        
//        // 多张图片
//        layout.minimumInteritemSpacing = CZStatusPictureMargin
//        layout.minimumLineSpacing = CZStatusPictureMargin
//        
//        // 默认3列
//        var column = CZStatusPictureMaxColumn
//        
//        // 有些情况只有2列
//        if count == 2 || count == 4 {
//            column = 2
//        }
//        
//        // 计算总行数, 一定要注意:column是整数,取整
//        // 2 + 2 - 1 / 2 = 1
//        // 3 + 3 - 1 / 3 = 1
//        // 4 + 3 - 1 / 3 = 2
//        // 5 + 3 - 1 / 3 = 2
//        //...
//        // 9 + 3 - 1 / 3 = 3
//        let row = (count + column - 1) / column
//        
//        // 计算宽度 cell的宽度 * 列数 + (列数 - 1) * cell之间的间距
//        let width = CZStatusPictureCellWH * CGFloat(column) + (CGFloat(column) - 1) * CZStatusPictureMargin
//        
//        // 计算高度 cell的高度 * 行数 + (行数 - 1) * cell之间的间距
//        let height = CZStatusPictureCellWH * CGFloat(row) + (CGFloat(row) - 1) * CZStatusPictureMargin
//        return CGSize(width: width, height: height)
//    }
//    
//    /// 布局
//    private let layout = UICollectionViewFlowLayout()
//    
//    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
//    
//    init() {
//        super.init(frame: CGRectZero, collectionViewLayout: layout)
//        // 默认是true,如果一个控制器的view里面只有一个UIScrollView/子类,当点击状态栏scrollsToTop=true是可以滚动到顶部
//        self.scrollsToTop = false
//        // 配图视图设置数据源,谁成为数据源都可以只要实现UICollectionViewDataSource
//        self.dataSource = self
//        self.delegate = self
//        self.registerClass(CZStatusPictureViewCell.self, forCellWithReuseIdentifier: ReuseIdentifier)
//        self.backgroundColor = UIColor.clearColor()
//    }
//}

//extension CZStatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
//    // 返回collectionView cell的数量
//    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        return pictureURLs?.count ?? 0
//    }
//    
//    // 返回每个cell的样子
//    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
//        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! CZStatusPictureViewCell
//        
////        cell.backgroundColor = UIColor.random()
//        // 给cell设置图片的NSURL地址
//        cell.imageURL = pictureURLs?[indexPath.item]
//        
//        return cell
//    }
//    
//    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//        let browser = SDPhotoBrowser()
//        
//        browser.sourceImagesContainerView = collectionView
//        
//        browser.imageCount = pictureURLs?.count ?? 0
//        
//        browser.currentImageIndex = indexPath.item
//        
//        browser.delegate = self
//        
//        browser.show()
//    }
//}

//extension CZStatusPictureView: SDPhotoBrowserDelegate {
//    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
//        let cell = cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as! CZStatusPictureViewCell
//        let image = cell.bkgImageView.image
//        return image ?? UIImage(named: "avatar")
//    }
//    
//    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
//        let urlString = pictureURLs![index].absoluteString
//        
//        let newString = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
//        return NSURL(string: newString)
//    }
//}

//// MARK: - 自定义cell
//class CZStatusPictureViewCell: UICollectionViewCell {
//    
//    // MARK: - 属性
//    /// 图片的URL地址
//    var imageURL: NSURL? {
//        didSet {
//            
//            // 使用SDWebImage来设置图片
//            if let url = imageURL {
//                bkgImageView.sd_setImageWithURL(url, placeholderImage: nil, options: SDWebImageOptions.AvoidAutoSetImage, completed: { (image, error, _, _) -> Void in
//                    if error != nil {
//                        print("error: \(error)")
//                        return
//                    }
//                    
//                    self.bkgImageView.image = image
//                    let width: CGFloat = image.size.width;
//                    let height: CGFloat = image.size.height;
//                    let scale = (height / width) / (self.bkgImageView.frame.height / self.bkgImageView.frame.width);
//                    if (scale < 0.99 || isnan(scale)) { // 宽图把左右两边裁掉
//                        self.bkgImageView.contentMode = UIViewContentMode.ScaleAspectFill
//                        self.bkgImageView.layer.contentsRect = CGRectMake(0, 0, 1, 1);
//                    } else { // 高图只保留顶部
//                        self.bkgImageView.contentMode = UIViewContentMode.ScaleAspectFill
//                        self.bkgImageView.layer.contentsRect = CGRectMake(0, 0, 1, width / height);
//                    }
//                })
//            }
//        }
//    }
//    
//    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
//    
//    override init(frame: CGRect) {
//        super.init(frame: frame)
//        
//        prepareUI()
//    }
//    
//    private func prepareUI() {
//        // 添加子控件
//        contentView.addSubview(bkgImageView)
//        
//        // 添加约束
//        bkgImageView.snp_makeConstraints { (make) -> Void in
//            make.edges.equalTo(contentView)
//        }
//        
//        // 设置bkgImageView的内容填充模式
//        bkgImageView.contentMode = UIViewContentMode.ScaleAspectFill
//        
//        // 超出imageView的剪掉
//        bkgImageView.clipsToBounds = true
//    }
//    
//    // MARK: - 懒加载
//    /// 背景图片
//    private lazy var bkgImageView: UIImageView = UIImageView()
//}
